from django.contrib.auth.models import User
from django.db import models
from django.contrib.auth.models import User
from .utils import send_dingtalk_message


class Task(models.Model):
    STATUS_CHOICES = (
        ('todo', 'To Do'),
        ('in_progress', 'In Progress'),
        ('done', 'Done'),
    )

    PROGRESS_CHOICES = (
        ('0', '0%'),
        ('10', '10%'),
        ('20', '20%'),
        ('30', '30%'),
        ('40', '40%'),
        ('50', '50%'),
        ('60', '60%'),
        ('70', '70%'),
        ('80', '80%'),
        ('90', '90%'),
        ('100', '100%'),
    )

    # 基本任务信息
    title = models.CharField(max_length=200, verbose_name="标题", db_comment="标题")
    description = models.TextField(blank=True, verbose_name="描述", db_comment="描述")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='todo', verbose_name="状态",
                              db_comment="状态")

    # 项目信息
    Projectname = models.CharField(max_length=200, blank=True, null=True, verbose_name="项目名称",
                                   db_comment="项目名称")
    system = models.CharField(max_length=200, blank=True, null=True, verbose_name="系统", db_comment="系统")

    # 人员角色
    ProjectManager = models.CharField(max_length=100, blank=True, null=True, verbose_name="项目经理",
                                      db_comment="项目经理")
    ProductManager = models.CharField(max_length=100, blank=True, null=True, verbose_name="产品经理",
                                      db_comment="产品经理")
    DevelopmentEngineer = models.CharField(max_length=100, blank=True, null=True, verbose_name="开发工程师",
                                           db_comment="开发工程师")
    TestEngineer = models.CharField(max_length=100, blank=True, null=True, verbose_name="测试工程师",
                                    db_comment="测试工程师")

    # 链接
    Demandlink = models.URLField(blank=True, null=True, verbose_name="需求链接", max_length=500, db_comment="需求链接")
    Testlink = models.URLField(blank=True, null=True, verbose_name="测试链接", max_length=500, db_comment="测试链接")

    # 日期和进度
    startdate = models.DateField(null=True, blank=True, verbose_name="开始日期", db_comment="开始日期")
    enddate = models.DateField(null=True, blank=True, verbose_name="结束日期", db_comment="结束日期")
    due_date = models.DateField(null=True, blank=True, verbose_name="截止日期", db_comment="截止日期")
    testschedule = models.CharField(max_length=200, blank=True, null=True, verbose_name="测试计划",
                                    db_comment="测试计划")
    testprogress = models.CharField(max_length=3, choices=PROGRESS_CHOICES, default='0', verbose_name="测试进度",
                                    db_comment="测试进度")

    # 其他数据
    Picturedata = models.ImageField(upload_to='task_images/', blank=True, null=True, verbose_name="图片数据",
                                    db_comment="图片数据")
    Remarks = models.TextField(blank=True, null=True, verbose_name="备注", db_comment="备注")

    # 测试过程
    Testingprocess = models.TextField(blank=True, null=True, verbose_name="测试过程", db_comment="测试过程")
    # excel  文件
    excel_file = models.FileField(upload_to='files/', blank=True, null=True, verbose_name="Excel文件",
                                  db_comment="Excel文件")

    # 系统字段
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间", db_comment="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间", db_comment="更新时间")
    assigned_to = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='assigned_tasks', null=True,
                                    blank=True, verbose_name="分配给", db_comment="分配给")
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='created_tasks', null=True, blank=True,
                                   verbose_name="创建者", db_comment="创建者")

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['due_date', 'status']
        verbose_name = "任务"
        verbose_name_plural = "任务"

    def save(self, *args, **kwargs):
        # 检查是否是新创建的任务
        is_new = self.pk is None

        # 保存任务
        super().save(*args, **kwargs)

        # 如果是新任务且设置了截止日期，发送通知
        if is_new and self.due_date and hasattr(self, '_send_notification') and self._send_notification:
            self.send_creation_notification()

    def send_creation_notification(self):
        """发送任务创建通知"""
        message = f"### 📋 新任务创建通知 \n\n"
        message += f"**任务标题**: {self.title} \n"
        message += f"**项目**: {self.Projectname or '未指定'} \n"
        message += f"**系统**: {self.system or '未指定'} \n"

        if self.assigned_to:
            message += f"**负责人**: {self.assigned_to.username} \n"
        else:
            message += f"**负责人**: 未分配 \n"

        if self.due_date:
            message += f"**截止日期**: {self.due_date.strftime('%Y-%m-%d')} \n"

        # 添加任务描述
        if self.description:
            # 截取描述的前100个字符
            short_desc = self.description[:100] + "..." if len(self.description) > 100 else self.description
            message += f"**描述**: {short_desc} \n"

        # 发送钉钉通知
        send_dingtalk_message(message)


class TaskImage(models.Model):
    task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='images', verbose_name='关联任务')
    image = models.ImageField(upload_to='task_images/', verbose_name='图片')
    caption = models.CharField(max_length=200, blank=True, null=True, verbose_name='图片说明')
    uploaded_at = models.DateTimeField(auto_now_add=True, verbose_name='上传时间')

    class Meta:
        verbose_name = '任务图片'
        verbose_name_plural = '任务图片'
        ordering = ['uploaded_at']

    def __str__(self):
        return f"{self.task.title} - 图片 {self.id}"


class TaskActivity(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    activity_type = models.CharField(max_length=255)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.user.username} - {self.activity_type} at {self.timestamp}"
